package com.chagee.channel.server.config;

import com.chagee.channel.common.constant.CommonConstant;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import org.slf4j.MDC;

import java.util.UUID;

/**
 * @author yangyang
 * @Description 过滤器传递tradeId（消费者和生产者）
 * @Version v1.0
 */
@Activate(group = { CommonConstants.PROVIDER,CommonConstants.CONSUMER})
public class GlobalTraceFilter implements Filter {

	@Override
	public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
		RpcContext rpcContext = RpcContext.getContext();
		String traceId;
		String replace = UUID.randomUUID().toString().replace("-", "");
		if (rpcContext.isConsumerSide()) {
			traceId = MDC.get(CommonConstant.TRACE_ID);
			if (traceId == null) {
				traceId = replace;
			}
			rpcContext.setAttachment(CommonConstant.TRACE_ID, traceId);
		}else if (rpcContext.isProviderSide()) {
			traceId = rpcContext.getAttachment(CommonConstant.TRACE_ID);
			if (traceId == null) {
				traceId = replace;
			}
			MDC.put(CommonConstant.TRACE_ID, traceId);
		}
		return invoker.invoke(invocation);
	}
}
